package com.smiier.skin.ui;

import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import cn.o.app.ui.OBadgeView;
import cn.skinapp.R;

import com.smiier.skin.constant.Constant;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.utils.DBUtil;
import com.smiier.skin.vo.TipMessageVo;

public class PersonalPatientFragment extends BasicFragment {

	private OBadgeView badge;
	protected View mBadgeTarget;

	public PersonalPatientFragment(Context context) {
		super(context);
	}

	public PersonalPatientFragment(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public PersonalPatientFragment(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
	}

	public void setBageViewTarget(View v) {
		mBadgeTarget = v;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		PersonalPatientView patientView = new PersonalPatientView(getContext());
		patientView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		this.setContentView(patientView);

		badge = new OBadgeView(getContext(), mBadgeTarget);

		badge.setBackgroundResource(R.drawable.no_read_point);

		badge.setBadgeMargin(CommonUtility.dip2px(getContext(), 20),
				CommonUtility.dip2px(getContext(), 5));

		badge.setHeight(1);
		badge.setWidth(1);

		IntentFilter noReadTab = new IntentFilter(
				Constant.RECIVER_MYIFNO_TAB_NOREAD);
		getContext().registerReceiver(noRead, noReadTab);

		initView();

	}

	private void initView() {
		DBUtil dbUtil = null;
		if (dbUtil == null) {
			dbUtil = DBUtil.getInstance(getContext());
		}

		ArrayList<TipMessageVo> list = dbUtil.query(TipMessageVo.class);

		int noReadNumber = 0;

		if (!list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {

				if (list.get(i).readState == 0) {
					noReadNumber++;
				}
			}

		}

		Log.i("testcount", "count:" + noReadNumber);

		if (noReadNumber > 0) {
			if (!badge.isShown()) {
				badge.show();
			}
		}

	}

	BroadcastReceiver noRead = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			boolean isShow = intent.getBooleanExtra("show", false);

			Log.i("testmy", "ishow:" + intent.getBooleanExtra("show", false));

			if (isShow) {
				badge.show();
			} else {
				badge.hide();
			}

		}
	};

	@Override
	public void onDestroy() {
		super.onDestroy();

		// if (noRead != null) {
		// getContext().unregisterReceiver(noRead);
		// }

	}

}
